package com.xingdata.jjxc.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.BuildConfig;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.ar_navi.ARHudComm;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.enty.HudVersionEntity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.file_service.FileMD5Checker;
import com.xingdata.jjxc.file_service.UploadLogService;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.utils.JUtils;
import com.xingdata.jjxc.utils.SDCardTools;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.callback.FileSizeCallBack;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.net.Socket;
import java.security.MessageDigest;
import java.util.HashMap;

import jar.tools.UdpTools;

public class HudUpdateActivity extends Base1Activity implements OnClickListener {

	private String TAG = "HudUpdateActivity";
	private LinearLayout versionLayout;
	/**版本号*/
	private TextView version_name;
	/**是否连接hud*/
	private TextView version_info;
	/**升级文件大小316.76M*/
	private TextView file_size;
	/**点击下载按钮*/
	private Button download;
	/**下载百分比*/
	private TextView downdload_vurrent;
	private HudVersionEntity versionEntity;
	/**true已经下载，false未下载*/
	private boolean isDownload = false;
	private Handler mHandler;
	private ImageView hudImageView;
    private UploadLogService logService;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// CommunicationObserver.addContentStateListener(this);
		// CommunicationObserver.addListener(this);
		// doPost_getHUDVersion();
        logService = new UploadLogService(this);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				switch (msg.what) {
				case RequestCode.REQUESTCODE_STATE_CHANGE:
					switch (msg.getData().getInt("state")) {
					case 1:
						if (!version_info.getText().toString().equals("已连接")) {
							version_info.setText("已连接");
//							hudImageView.setBackgroundResource(R.drawable.hud_bg);
						}

						break;
					case 2:
						if (!version_info.getText().toString().equals("未连接")) {
							version_info.setText("未连接");
//							hudImageView.setBackgroundResource(R.drawable.hud_bg1);
						}
						break;

					default:
						break;
					}

					break;

				case RequestCode.REQUESTCODE_UPDATE_OK:
					dismissProgressDialog();
					String message;
					if (msg.getData().getInt("state") == 0) {
						message = "升级成功";
						SDCardTools.delAllFile(SDCardTools.getFilePath(SDCardTools.UPGRADEDATA_NAME));

					} else {
						message = "升级失败";
					}

					AlertDialog.Builder builder = new Builder(HudUpdateActivity.this);

					builder.setTitle("提示");
					builder.setMessage(message);
					builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialogInterface, int arg1) {
							dialogInterface.dismiss();
							finish();
						}
					});
					builder.create().show();
					break;
				default:
					break;
				}
			}
		};
	}
	
	@Override
	protected int getContentViewId() {
		return R.layout.hud_update;
	}

	@Override
	protected String getTitleText() {
		return "设备升级";
	}

	@Override
	protected void initViews() {
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
		((TextView) findViewById(R.id.hud_title)).setTypeface(font);
		((TextView) findViewById(R.id.file_size)).setTypeface(font);
		((TextView) findViewById(R.id.version_name)).setTypeface(font);
		((Button) findViewById(R.id.download)).setTypeface(font);
		((TextView) findViewById(R.id.downdload_vurrent)).setTypeface(font);

		version_info = (TextView) findViewById(R.id.version_info);
		version_info.setTypeface(font);
		versionLayout = (LinearLayout) findViewById(R.id.version_layout);
		file_size = (TextView) findViewById(R.id.file_size);
		version_name = (TextView) findViewById(R.id.version_name);
		
		download = (Button) findViewById(R.id.download);
		download.setOnClickListener(this);
		
		downdload_vurrent = (TextView) findViewById(R.id.downdload_vurrent);
		hudImageView = (ImageView) findViewById(R.id.hud_bg);
	}

    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }

	/**
	 * 获取HUD版本号
	 */
	private void doPost_getHUDVersion() {
		showProgressDialog("正在获取最新版本号");
		paramsMap = new HashMap<String, String>();
		if (UdpTools.getHudVersion() != null && UdpTools.getHudVersion().length() == 0) {
            paramsMap.put("version", UdpTools.getHudVersion());
		} else {
            paramsMap.put("version", SharedPreTools.getString(HudUpdateActivity.this, Common.HUD_VERSION, "hud_X1_000"));
		}

		if (paramsMap.get("version").length() != 0) {
			version_name.setText(paramsMap.get("version"));
		}

		HttpUtil.getInstance(this).Post(App.ZZD_REQUEST_GETHUDVERSION, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				versionEntity = JSON.parseObject(respEntity.getResult(), HudVersionEntity.class);
				HttpUtil.getInstance(HudUpdateActivity.this).getFileSize(new FileSizeCallBack() {

					@Override
					public void onFileSize(String strSize) {
						file_size.setText(strSize);
					}
				}, versionEntity.getVersion_path());

				version_name.setText(versionEntity.getVersion_name());
				File file = new File(SDCardTools.getFilePath(SDCardTools.UPGRADEDATA_NAME) + "/"
						+ SDCardTools.getFileName(versionEntity.getVersion_path()));

				// 判断文件是否存在
				if (file.isFile() && getFileMD5(file).compareToIgnoreCase(versionEntity.getFile_MDFive())==0) {
					isDownload = true;
					download.setText("发送至HUD");
				} else {
					// 如果没有先删除整个文件
					SDCardTools.delAllFile(SDCardTools.getFilePath(SDCardTools.UPGRADEDATA_NAME));
				}
				dismissProgressDialog();
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {
				Log.i(TAG, result);
				dismissProgressDialog();
				download.setVisibility(View.GONE);
				file_size.setText(result);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.download:
            // 点击推送 OTA数据包
            if(!isLoading){
                File otafile = new File("/sdcard/ds3_ota.zip");
                if(otafile.exists()){
                    Log.i(TAG,"===========> update data file exist");
                    uploadFile(otafile, ARHudComm.getInstance().getDeviceAddr().getHostAddress());
                    Toast.makeText( this, "正在开始升级，请耐心等待...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText( this, "/sdcard/hud_ota.zip 升级文件不存在!", Toast.LENGTH_LONG).show();
                }
            }else{
                // // TODO: 2016/10/28 Stop loading
            }
			break;

		default:
			break;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int tranfsferBytes = msg.getData().getInt("size");
            // uploadbar.setProgress(length);
            float percent = (float)tranfsferBytes/(float)totalBytes;
            int result = (int)(percent * 100);
            download.setText(result+"%");
//            txt_loading.setText(result+"%");TODO set the text
            if(result == 100){
                Toast.makeText(HudUpdateActivity.this, "设备进入OTA升级，请稍后重新连接设备热点!", Toast.LENGTH_LONG).show();
            }
        }
    };

    private boolean start = true;
    int totalBytes = 0;
    boolean isLoading = false;
    Thread loadingThread;
    Socket socket;
    /**
     * 上传OTA文件
     * @param uploadFile
     */
    private void uploadFile(final File uploadFile,final String deviceIp) {
        if(isLoading)
            return;

        totalBytes = (int)uploadFile.length();
        loadingThread= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i(TAG,"start update loading...to :"+deviceIp);

                    String souceid = logService.getBindId(uploadFile);
                    String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+
                            (souceid==null? "" : souceid)
                            +";md5="+ FileMD5Checker.calculateSingleFileMD5sum(uploadFile)
                            +"\r\n";
                    Log.i(TAG,"--------> file info: "+head);
                    socket = new Socket(deviceIp,30005);
                    OutputStream outStream = socket.getOutputStream();
                    outStream.write(head.getBytes());

                    RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
                    byte[] buffer = new byte[8*1024];
                    int len = -1;
                    int length = 0;
                    while(start&&(len = fileOutStream.read(buffer)) != -1){
                        outStream.write(buffer, 0, len);
                        length += len;
                        Message msg = new Message();
                        msg.getData().putInt("size", length);
                        handler.sendMessage(msg);
                        isLoading = true;
                        if(BuildConfig.DEBUG)
                            Log.e(TAG,"--------> loading:"+ 100 * (float)length /uploadFile.length());
                    }
                    fileOutStream.close();
                    outStream.close();
                    socket.close();
                    socket = null;
                    if(length==uploadFile.length()) logService.delete(uploadFile);
                    isLoading = false;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG,"--------> upload error: "+e.getMessage());
                    isLoading =false;
                }
            }
        });loadingThread.start();

    }
}
